<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Row Editing in DataGrid - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="../css/easyui.css">
    <link rel="stylesheet" type="text/css" href="../css/icon.css">
    <link rel="stylesheet" type="text/css" href="../css/demo.css">
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script type="text/javascript" src="../js/jquery.easyui.min.js"></script>
</head>
<body>
<h2>Row Editing in DataGrid</h2>
<p>Click the row to start editing.</p>
<div style="margin:20px 0;"></div>

<table id="dg" class="easyui-datagrid" title="Row Editing in DataGrid" style="width:700px;height:auto"
       data-options="
				iconCls: 'icon-edit',
				singleSelect: true,
				toolbar: '#tb',
				url: '/yhd/goods/list',
				pagination: true,
				method: 'get',
				onDblClickRow: onDblClickRow,
				onClickRow: onClickRow,
				onEndEdit: onEndEdit,
				pageList: [5,10,15,30],
				pageSize: 5
			">
    <thead>
    <tr>
        <th data-options="field:'gid',width:80,sortable:true">编号</th>
        <th data-options="field:'gname',width:100,sortable:true,editor:'textbox'">名称</th>
        <th data-options="field:'gprice',width:80,align:'right',sortable:true,editor:{type:'numberbox',options:{precision:1}}">
            价格
        </th>
        <th data-options="field:'description',width:200,align:'right',editor:'textbox'">描述</th>
        <th data-options="field:'num',width:100,editor:'textbox',sortable:true">库存</th>
        <th data-options="field:'goodType',width:60,align:'center',
            formatter:function formatGoodsType(val, row) {
                if (val == '1') return '电器';
                if (val == '2') return '家具';
                if (val == '3') return '玩具';
                if (val == '4') return '书籍';
                if (val == '5') return '服饰';
            },
            editor:{
                type:'combobox',options:{
                    url:'/yhd/dataDictionary/goodsType',
                    method:'get',
                    valueField:'valueId',
                    textField:'typeName',
                }
            }">
            类目
        </th>
    </tr>
    </thead>
</table>

<div id="tb" style="height:auto">
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true"
       onclick="add()">Add</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true"
       onclick="removeit()">Remove</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true"
       onclick="accept()">Accept</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-undo',plain:true"
       onclick="reject()">Reject</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true"
       onclick="getChanges()">GetChanges</a>
</div>
<div id="dlg" class="easyui-dialog" style="height: 400px;width: 500px;padding: 10px" closed="true"
     data-options="buttons: '#dlg-buttons'">
    <form id="fm" method="post">
        <div style="margin-bottom:5px">
            <input class="easyui-textbox" name="gname" label="商品名称:" labelPosition="top" data-options="prompt:'请输入商品名称',validType:'length[1,20]',required:true">
        </div>
        <div style="margin-bottom:5px">
            <input  class="easyui-numberbox" name="gprice" label="价格:" labelPosition="top" min="0.1" max="10000.00" precision="2" required="true">
        </div>
        <div style="margin-bottom:5px">
            <input  class="easyui-numberbox" name="num" label="库存:" labelPosition="top" min="0" max="10000">
        </div>
        <div style="margin-bottom:5px">
            <input class="easyui-combobox" name="goodType" label="类目" labelPosition="top" required="true" data-options="
                url:'/yhd/dataDictionary/goodsType',
                method:'get',
                valueField:'valueId',
                textField:'typeName',
            ">
        </div>
        <div style="margin-bottom:5px">
            <input class="easyui-textbox" name="description" label="描述:" labelPosition="top" data-options="validType:'length[0,300]',multiline:true">
        </div>
    </form>
    <div id="dlg-buttons">
        <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="addGood()">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">取消</a>
    </div>
</div>
<script type="text/javascript">

    var code = {
        add_success: 100,//添加成功
        add_error: 101,//添加失败

        del_success: 200,//删除成功
        del_error: 201,//删除失败

        update_success: 300,
        update_error: 301,

        unknown_error: -1//未知异常
    };
    var editIndex = undefined;
    function onDblClickRow(rowIndex, rowData) {
        if (editIndex == undefined) {
            $('#dg').datagrid("beginEdit", rowIndex);
            editIndex = rowIndex;
        }
    }
    function onClickRow(rowIndex, rowData) {
        if (editIndex != rowIndex) {
            $('#dg').datagrid("endEdit", editIndex);
        }
    }
    function onEndEdit(rowIndex, rowData, changes) {
        $.ajax({
            url: "/yhd/goods/update",
            type: 'PATCH',
            contentType: 'application/json;charset=utf-8',
            dataType: 'JSON',
            data: JSON.stringify(rowData),
            success: function (result) {
                if (result.code == code.update_success) {//如果返回成功code
                    $('#dg').datagrid('reload');    // 刷新页面
                } else {
                    $.messager.show({
                        title: "Error",
                        msg: result.msg + " " + result.data
                    });
                }
            }
        });
        editIndex = undefined;
    }
    //删除行
    function removeit(){
        $.messager.confirm("删除","是否删除该行",function(r){
            if(r){
                var row = $('#dg').datagrid("getSelected");
                $.post("/yhd/goods/delete/"+row.gid,function(result){
                    if (result.code==code.del_success){//如果返回成功code
                        $('#dg').datagrid('reload');    // 刷新页面
                        //下面是不刷新页面的写法
                        // editRow = datagrid.datagrid("getRowIndex", rows);
                        // datagrid.datagrid("cancelEdit",editRow).datagrid('deleteRow', editRow);
                        // editRow = undefined;
                    } else {
                        $.messager.show({
                            title: 'Error',
                            msg: result.msg // 显示错误信息
                        });
                    }
                },"json");
            }
        });
    }
    function add(){
        $('#dlg').dialog('open')
    }
    function addGood(){
        $('#fm').form('submit', {//调用form表单的submit
            url: '/yhd/goods/add',
            success: function (result) {
                if (result.code == code.add_error) {//如何返回错误code
                    $.messager.show({
                        title: 'Error',
                        msg: result.msg //显示错误信息
                    });
                } else {
                    $('#dlg').dialog('close'); // 成功就关闭对话框
                    $('#dg').datagrid('reload'); // 然后重新加载页面
                }
            }
        });
    }
    function accept(rowData) {
        if(editIndex!=undefined){
            $('#dg').datagrid("endEdit",editIndex);
        }
    }
    function reject(){
        $('#dg').datagrid('rejectChanges');
        editIndex = undefined;
    }
    /*function endEditing() {
        if (editIndex == undefined) {
            return true;
        }
        if ($('#dg').datagrid('validateRow', editIndex)) {
            $('#dg').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }
    function onClickCell(index, field) {
        if (editIndex != index) {
            if (endEditing()) {
                $('#dg').datagrid('selectRow', index)
                    .datagrid('beginEdit', index);
                var ed = $('#dg').datagrid('getEditor', {index: index, field: field});
                if (ed) {
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                }
                editIndex = index;
            } else {
                setTimeout(function () {
                    $('#dg').datagrid('selectRow', editIndex);
                }, 0);
            }
        }
    }

    function append() {
        if (endEditing()) {
            $('#dg').datagrid('appendRow', {status: 'P'});
            editIndex = $('#dg').datagrid('getRows').length - 1;
            $('#dg').datagrid('selectRow', editIndex)
                .datagrid('beginEdit', editIndex);
        }
    }
    function removeit() {
        if (editIndex == undefined) {
            return
        }
        $('#dg').datagrid('cancelEdit', editIndex)
            .datagrid('deleteRow', editIndex);
        editIndex = undefined;
    }
    function accept() {
        if (endEditing()) {
            $('#dg').datagrid('acceptChanges');
        }
    }
    function reject() {
        $('#dg').datagrid('rejectChanges');
        editIndex = undefined;
    }
    function getChanges() {
        var rows = $('#dg').datagrid('getChanges');
        alert(rows.length + ' rows are changed!');
    }*/
</script>
</body>
</html>